module Wondercap
  
  class TaskExecutorError < RuntimeError
    attr_reader :executor, :errors
    
    def initialize(executor)
      @executor = executor
      @errors = {}
    end
    
    def [](key)
      @errors[key]
    end
    
    def message
      lines = []
       @errors.each_pair do |k,v|
         lines << "#{k.fetch(:configuration_name, "[unknown configuration]")}: #{v.message}"
       end
       lines.join("\n")
    end
    
  end
  
  module TaskExecutor
    module_function
    def execute(task, configurations, options = {})
      executor_error = TaskExecutorError.new(self)
      configurations.each do |conf|
        begin
          conf.find_and_execute_task(task)
          conf.trigger :task_succeeded, conf.find_task(task)
        rescue => e
          conf.logger.important e.to_s
          conf.logger.debug e.backtrace.join("\t\n")
          executor_error.errors[conf] = e
          conf.trigger :task_failed, conf.find_task(task)
          break unless options[:ignore_errors]
        end
      end
      raise executor_error unless executor_error.errors.empty?
    end
  end
  
end